"""
应用配置管理
"""
from typing import List, Optional
from pydantic import Field
from pydantic_settings import BaseSettings
from dotenv import load_dotenv
import os

# 确保加载 .env 文件
load_dotenv()


class RedisSettings(BaseSettings):
    """Redis配置"""
    host: str = Field(default=os.getenv("REDIS_HOST", "localhost"))
    port: int = Field(default=int(os.getenv("REDIS_PORT", "6379")))
    password: str = Field(default=os.getenv("REDIS_PASSWORD", "123456"))
    db: int = Field(default=int(os.getenv("REDIS_DB", "0")))
    max_connections: int = Field(default=int(os.getenv("REDIS_MAX_CONNECTIONS", "20")))
    
    @property
    def url(self) -> str:
        """Redis连接URL"""
        if self.password:
            return f"redis://:{self.password}@{self.host}:{self.port}/{self.db}"
        return f"redis://{self.host}:{self.port}/{self.db}"


class KafkaSettings(BaseSettings):
    """Kafka配置"""
    bootstrap_servers: str = Field(default=os.getenv("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"))
    security_protocol: str = Field(default=os.getenv("KAFKA_SECURITY_PROTOCOL", "PLAINTEXT"))
    sasl_mechanism: str = Field(default=os.getenv("KAFKA_SASL_MECHANISM", "PLAIN"))
    sasl_username: Optional[str] = Field(default=os.getenv("KAFKA_SASL_USERNAME"))
    # 消费者组配置 - 确保不影响其他系统
    consumer_group_prefix: str = Field(default=os.getenv("KAFKA_CONSUMER_GROUP_PREFIX", "kmsg-ui-viewer"))
    sasl_password: Optional[str] = Field(default=os.getenv("KAFKA_SASL_PASSWORD"))

    @property
    def servers_list(self) -> List[str]:
        """Kafka服务器列表"""
        return [server.strip() for server in self.bootstrap_servers.split(",")]


class AppSettings(BaseSettings):
    """应用配置"""
    name: str = Field(default="kmsg-ui", env="APP_NAME")
    version: str = Field(default="1.0.0", env="APP_VERSION")
    debug: bool = Field(default=True, env="DEBUG")
    log_level: str = Field(default="INFO", env="LOG_LEVEL")


class APISettings(BaseSettings):
    """API配置"""
    host: str = Field(default="0.0.0.0", env="API_HOST")
    port: int = Field(default=8000, env="API_PORT")
    reload: bool = Field(default=True, env="API_RELOAD")
    cors_origins: List[str] = Field(
        default=["http://localhost:3000", "http://localhost:5173"],
        env="CORS_ORIGINS"
    )
    allowed_hosts: List[str] = Field(default=["*"], env="ALLOWED_HOSTS")


class WebSocketSettings(BaseSettings):
    """WebSocket配置"""
    heartbeat_interval: int = Field(default=30, env="WS_HEARTBEAT_INTERVAL")
    max_connections: int = Field(default=1000, env="WS_MAX_CONNECTIONS")
    message_queue_size: int = Field(default=10000, env="WS_MESSAGE_QUEUE_SIZE")


class PerformanceSettings(BaseSettings):
    """性能配置"""
    stream_batch_size: int = Field(default=100, env="STREAM_BATCH_SIZE")
    stream_timeout: float = Field(default=5.0, env="STREAM_TIMEOUT")
    cache_ttl: int = Field(default=300, env="CACHE_TTL")
    max_message_size: int = Field(default=1048576, env="MAX_MESSAGE_SIZE")


class MonitoringSettings(BaseSettings):
    """监控配置"""
    enable_metrics: bool = Field(default=True, env="ENABLE_METRICS")
    metrics_port: int = Field(default=9090, env="METRICS_PORT")


class Settings(BaseSettings):
    """主配置类"""
    redis: RedisSettings = Field(default_factory=RedisSettings)
    kafka: KafkaSettings = Field(default_factory=KafkaSettings)
    app: AppSettings = Field(default_factory=AppSettings)
    api: APISettings = Field(default_factory=APISettings)
    websocket: WebSocketSettings = Field(default_factory=WebSocketSettings)
    performance: PerformanceSettings = Field(default_factory=PerformanceSettings)
    monitoring: MonitoringSettings = Field(default_factory=MonitoringSettings)

    model_config = {
        "env_file": ".env",
        "env_file_encoding": "utf-8",
        "extra": "ignore"
    }


# 全局配置实例
settings = Settings()

def get_settings() -> Settings:
    """获取配置实例"""
    return settings
